package com.lyhengtongwl.zqsnews.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.entity.UserContactsBo;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Response;

public class PhoneUtils {

    // 号码
    private String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
    // 联系人姓名
    private String NAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
    private Context context;
    //上下文对象
    //联系人提供者的uri
    private Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;

    public PhoneUtils(Context context) {
        this.context = context;
    }


    //获取所有联系人
    public void upLoadPhones() {
        try {
            List<UserContactsBo> phones = new ArrayList<>();
            String userId = SPUtils.get(App.getContext(), "userId", "") + "";
            if (!userId.equals("")) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        ContentResolver cr = context.getContentResolver();
                        @SuppressLint("Recycle") Cursor cursor = cr.query(phoneUri, new String[]{NUM, NAME}, null, null, null);
                        assert cursor != null;
                        while (cursor.moveToNext()) {
                            UserContactsBo phoneDto = new UserContactsBo(cursor.getString(cursor.getColumnIndex(NAME)), cursor.getString(cursor.getColumnIndex(NUM)), userId);
                            phones.add(phoneDto);

                        }
                        Task.getApiService().upLoadContacts(phones).enqueue(new MyCallback<NewsBaseEntity>((Activity) context) {
                            @Override
                            protected void onSuccess(Response<NewsBaseEntity> response) {
//                            Log.e("uploadPhone", "上传通讯录成功！");
                            }

                            @Override
                            protected void onFailure(Throwable t) {

                            }
                        });
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}